var axios = require('axios');
var token = ''
module.exports = {
  schedule: {
    interval: '1s', // 1 s间隔
    type: 'all', // 指定所有的 worker 都需要执行
  },
  async task(ctx) {
    const mxid = '1x9y79czMwU'   // 物模型id
    const uuid = '1BjRe9JAmti'   // 物实例id
    axios.get(`https://openapi.rootcloud.com/realtime-manage/v1/realtime/models/${mxid}/things/${uuid}`, {
      headers: {
        Authorization: token
      }
    }
    )
      .then(res => {
        var data = res.data.payload[0].data
        var _data = {}

        for (const key in data) {
          _data[key] = data[key].value
        }

        // console.log('===', _data)
        ctx.model.Device.create(_data);  // 写入mongodb
        // console.log(_data)
        // 发送到根云积木
        // axios.post('http://lowcode.skills-rootcloud.com:8880/api/workflow/hooks/NjcxYzg1YzhkYzY5NjkxOTFkOTViYzUy', {
        //   ..._data
        // }).then(res => {
        //   // console.log(res)
        // })

      })
      .catch(err => {
        // 如果登录失效，重新获取token
        if (err.status === 401) {
          axios.post('https://openapi.rootcloud.com/account-manage/v2/auth/login', {
            grant_type: 'client_credentials',
            client_id: '202406200c53f10d3487cc0d',
            client_secret: 'fb1952542028b8c322ab0aedb036445f'
          }).then(res => {
            token = 'Bearer ' + res.data.access_token
          })
        }
      })
  },
};